//
//  BuyViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/13.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "BuyViewController.h"
#import "SelectAddressTableViewCell.h"
#import "OrderTableViewCell.h"
#import "BuyItemTableViewCell.h"
#import "BuyTypeViewController.h"
#import "ExpressViewController.h"
#import "BillInfoViewController.h"
#import "ZhiFuViewController.h"
#import "CartModel.h"
#import "AddressViewController.h"
#import "AddressModel.h"
#import "BuyGoodsItemTableViewCell.h"
#import "SelectCouponsViewController.h"

@interface BuyViewController ()<UITableViewDelegate,UITableViewDataSource,AddressViewControllerDelegate,BuyTypeViewControllerDelegate,ExpressViewControllerDelegate,BillInfoViewControllerDelegate,SelectCouponsViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSDictionary *jieSuanDic;

@property (nonatomic, strong) AddressModel *addressModel; // 选中地址
@property (nonatomic, strong) NSMutableArray *payTypeArray; // 支付方式
@property (nonatomic, strong) NSDictionary *payDic; // 选中支付方式
@property (nonatomic, strong) NSMutableArray *expressageArray; // 送货方式
@property (nonatomic, strong) NSDictionary *expressageDic; // 选中送货方式
@property (nonatomic, strong) NSDictionary *billDic; // 选中发票信息
@property (nonatomic, strong) NSDictionary *couponsDic; // 选中优惠券
@property (nonatomic, strong) UITextField *textField; // 买家留言
@property (nonatomic, strong) NSMutableArray *couponsArray;

@end

@implementation BuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tableViewBgColor;
    [self loadBaseTitleLable:@"确认订单"];
    [self setUpUI];
    [self confirmOrder];
}
- (void)setUpUI
{
    [self.view addSubview:self.tableView];
    
    UIButton *btn = [UIButton buttonWithTitle:@"提交订单" fontSize:14 titleColor:UIColorWhite background:navBarColor cornerRadius:5];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-rateHeight(50));
        make.size.mas_offset(CGSizeMake(rateWidth(630), rateHeight(100)));
    }];
    [btn addTarget:self action:@selector(tiJiaoOrder) forControlEvents:(UIControlEventTouchUpInside)];
}
#pragma mark - 获取优惠券
- (void)getCouponListData
{
    CGFloat sumPrice = 0.0;
    NSArray *array = self.jieSuanDic[@"shopList"];
    if (array.count != 0) {
        for (NSDictionary *dic in array) {
            sumPrice = sumPrice + [dic[@"CommodityZPrice"] floatValue];
        }
    }
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/vouchers.ashx?action=couponlist&companyid=%@&code=%@&timestamp=%@&pagesize=100000&pageindex=1&status=%@&money=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],@"1",@(sumPrice)] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            self.couponsArray = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                [self.couponsArray addObject:dic];
            }
        } else {
            
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
#pragma mark - 确认订单
- (void)confirmOrder
{
    if (self.selectIdArray.count != 0) {
        //        NSMutableArray *array = [NSMutableArray array];
        //        for (CartModel *model in self.selectArray) {
        //            [array addObject:model.CartId];
        //        }
        [MBProgressHUD showMessage:nil toView:self.view];
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=checkout&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"cartid":[self.selectIdArray componentsJoinedByString:@","],@"from":@"mobile"} success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            if (responseObject) {
                if ([responseObject[@"status"] intValue] == 1) {
                    self.jieSuanDic = responseObject;
                    // 地址
                    if (responseObject[@"address"]) {
                        NSArray *array = responseObject[@"address"];
                        for (NSDictionary *dic in array) {
                            if ([dic[@"addressDefault"] intValue] == 1) {
                                // 默认地址
                                self.addressModel = [[AddressModel alloc] init];
                                [self.addressModel setValuesForKeysWithDictionary:dic];
                            }
                        }
                    }
                    // 支付方式
                    if (responseObject[@"PaymentTypeList"]) {
                        NSArray *array = responseObject[@"PaymentTypeList"];
                        self.payTypeArray = [NSMutableArray array];
                        for (NSDictionary *dic in array) {
                            [self.payTypeArray addObject:dic];
                        }
                        self.payDic = self.payTypeArray[0];
                    }
                    // 送货方式
                    if (responseObject[@"express"]) {
                        NSArray *array = responseObject[@"express"];
                        self.expressageArray = [NSMutableArray array];
                        for (NSDictionary *dic in array) {
                            [self.expressageArray addObject:dic];
                        }
                        self.expressageDic = self.expressageArray[0];
                    }
                    // 获取优惠券
                    [self getCouponListData];
                }
            }
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [TFHUD addRemindHUD:self.view message:@"保存失败,请检查网络"];
        }];
    }
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        NSArray *array = self.jieSuanDic[@"shopList"];
        return array.count;
    } else if (section == 2) {
        return 4;
    } else if (section == 3) {
        return 1;
    } else {
        return 4;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        SelectAddressTableViewCell *cell = [[SelectAddressTableViewCell alloc] init];
        // 赋值
        if (self.addressModel) {
            cell.nameLB.text = [NSString stringWithFormat:@"%@  %@",self.addressModel.addressName,self.addressModel.addressPhone];
            cell.addressLB.text = [NSString stringWithFormat:@"地址：%@%@%@%@",self.addressModel.addressProvince,self.addressModel.addressCity,self.addressModel.addressArea,self.addressModel.addressXX];
            if ([self.addressModel.addressDefault intValue] == 1) {
                cell.tagLB.hidden = NO;
            } else {
                cell.tagLB.hidden = YES;
            }
        }
        
        cell.selectionStyle = NO;
        return cell;
    } else if (indexPath.section == 1) {
        BuyGoodsItemTableViewCell *cell = [[BuyGoodsItemTableViewCell alloc] init];
        // 赋值
        NSArray *array = self.jieSuanDic[@"shopList"];
        if (array.count != 0) {
            NSDictionary *dic = array[indexPath.row];
            cell.topLB.text = dic[@"CommodityName"];
            [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"CartImg"]]]];
            cell.goodsTitleLB.text = [NSString stringWithFormat:@"优惠金额：￥%.2f",[dic[@"CommodityYhPrice"] floatValue]];
            cell.describeLB.text = dic[@"CommodityProperty"];
            cell.priceLB.text = [NSString stringWithFormat:@"原价：￥%.2f",[dic[@"CommodityXPrice"] floatValue]];
            cell.numLB.text = [NSString stringWithFormat:@"×%@",dic[@"CommodityNumber"]];
            cell.bottomPrice.text = [NSString stringWithFormat:@"当前价：￥%.2f",[dic[@"CommodityZPrice"] floatValue]];
        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        BuyItemTableViewCell *cell = [[BuyItemTableViewCell alloc] init];
        if (indexPath.section == 2) {
            NSString *bill;
            if (self.billDic) {
                bill = self.billDic[@"text"];
            } else {
                bill = @"不开发票";
            }
            NSArray *array1 = @[@"支付方式",@"送货方式",@"发票信息",@"优惠券"];
            
            NSString *payType;
            NSString *kuaiDi;
            NSString *couponsStr;
            if (self.payDic[@"PaymentName"]) {
                payType = [NSString stringWithFormat:@"%@",self.payDic[@"PaymentName"]];
            } else {
                payType = @"支付方式";
            }
            if (self.expressageDic[@"kdname"]) {
                kuaiDi = [NSString stringWithFormat:@"%@",self.expressageDic[@"kdname"]];
            } else {
                kuaiDi = @"送货方式";
            }
            if (self.couponsArray.count == 0) {
                couponsStr = @"无可用优惠券";
            } else {
                
                if (self.couponsDic[@"Qmoney"]) {
                    couponsStr = [NSString stringWithFormat:@"-￥%.2f",[self.couponsDic[@"Qmoney"] floatValue]];
                } else {
                    couponsStr = @"选择优惠券";
                }
            }
            
            NSArray *array2 = @[payType,kuaiDi,[NSString stringWithFormat:@"%@",bill],couponsStr];
            cell.leftLB.text = array1[indexPath.row];
            cell.rightLB.text = array2[indexPath.row];
        } else if (indexPath.section == 4) {
            cell.redLB.hidden = NO;
            cell.arrow.hidden = YES;
            cell.rightLB.hidden = YES;
            NSArray *array1 = @[@"累计商品金额：",@"累计优惠金额：",@"发所需运费价格：",@"合计应付金额："];
            NSString *leiJiYouHui;
            NSString *heJi;
            if (self.couponsDic[@"Qmoney"]) {
                leiJiYouHui = [NSString stringWithFormat:@"-￥%.2f",[self.jieSuanDic[@"totalZkPrice"] floatValue]+[self.couponsDic[@"Qmoney"] floatValue]];
                heJi = [NSString stringWithFormat:@"￥%.2f",([self.jieSuanDic[@"totalPrice"] floatValue]-[self.jieSuanDic[@"totalZkPrice"] floatValue]+[self.expressageDic[@"KdYfPrice"] floatValue]-[self.couponsDic[@"Qmoney"] floatValue])];
            } else {
                leiJiYouHui = [NSString stringWithFormat:@"-￥%.2f",[self.jieSuanDic[@"totalZkPrice"] floatValue]];
                heJi = [NSString stringWithFormat:@"￥%.2f",([self.jieSuanDic[@"totalPrice"] floatValue]-[self.jieSuanDic[@"totalZkPrice"] floatValue]+[self.expressageDic[@"KdYfPrice"] floatValue])];
            }
            NSArray *array2 = @[[NSString stringWithFormat:@"￥%.2f",[self.jieSuanDic[@"totalPrice"] floatValue]],leiJiYouHui,[NSString stringWithFormat:@"+￥%.2f",[self.expressageDic[@"KdYfPrice"] floatValue]],heJi];
            cell.leftLB.text = array1[indexPath.row];
            cell.redLB.text = array2[indexPath.row];
        } else {
            cell.leftLB.text = @"买家留言";
            cell.arrow.hidden = YES;
            cell.rightLB.hidden = YES;
            UITextField *textField = [[UITextField alloc] init];
            textField.placeholder = @"选填：对本次交易的说明";
            textField.font = UIFontSystem(13);
            textField.textColor = UIColorFromRGB(0x323232);
            [cell.contentView addSubview:textField];
            [textField mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView);
                make.left.equalTo(cell.leftLB.mas_right).offset(rateWidth(20));
                make.size.mas_offset(CGSizeMake(rateWidth(590), rateHeight(80)));
            }];
            self.textField = textField;
        }
        cell.selectionStyle = NO;
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return rateHeight(150);
    } else if (indexPath.section == 1) {
        return rateHeight(350);
    } else {
        return rateHeight(90);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 0.01;
    } else if (section == 2) {
        return rateHeight(2);
    } else {
        return 0.01;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return rateHeight(10);
    } else if (section == 1) {
        return 0.01;
    } else if (section == 4) {
        return rateHeight(200);
    } else {
        return rateHeight(10);
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    if (section == 4) {
        bgV.backgroundColor = tableViewBgColor;
    }
    return bgV;
}
#pragma mark - 提交订单
- (void)tiJiaoOrder
{
    if (self.selectIdArray.count != 0) {
        //        NSMutableArray *array = [NSMutableArray array];
        //        for (CartModel *model in self.selectArray) {
        //            [array addObject:model.CartId];
        //        }
        // 收货地址
        if (self.addressModel) {
            // 发票
            NSString *faPiao;
            NSString *faPiaoBeiZhu = @"";
            if (self.billDic) {
                if ([self.billDic[@"text"] isEqualToString:@"不开发票"]) {
                    faPiao = @"1";
                } else if ([self.billDic[@"text"] isEqualToString:@"个人"]) {
                    faPiao = @"2";
                    if (self.billDic[@"remark"]) {
                        faPiaoBeiZhu = self.billDic[@"remark"];
                    }
                } else if ([self.billDic[@"text"] isEqualToString:@"企业"]) {
                    faPiao = @"3";
                    if (self.billDic[@"remark"]) {
                        faPiaoBeiZhu = self.billDic[@"remark"];
                    }
                }
            } else {
                faPiao = @"1";
            }
            
            [MBProgressHUD showMessage:nil toView:self.view];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/shop/shop.ashx?action=ordersubmit&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"cartid":[self.selectIdArray componentsJoinedByString:@","],@"addressid":self.addressModel.addresslId,@"paymentname":_payDic[@"PaymentName"],@"ordertype":self.expressageDic[@"kdname"],@"invoicestatus":faPiao,@"invoicename":faPiaoBeiZhu,@"remark":self.textField.text,@"from":@"mobile"} success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if (responseObject) {
                    if ([responseObject[@"status"] intValue] == 1) {
                        ZhiFuViewController *zhiFuVC = [[ZhiFuViewController alloc] init];
                        zhiFuVC.orderNumber = responseObject[@"orderNumber"];
                        if (self.couponsDic[@"Qmoney"]) {
                            zhiFuVC.payMoney = [NSString stringWithFormat:@"￥%.2f",([self.jieSuanDic[@"totalPrice"] floatValue]-[self.jieSuanDic[@"totalZkPrice"] floatValue]+[self.expressageDic[@"KdYfPrice"] floatValue]-[self.couponsDic[@"Qmoney"] floatValue])];
                        } else {
                            zhiFuVC.payMoney = [NSString stringWithFormat:@"￥%.2f",([self.jieSuanDic[@"totalPrice"] floatValue]-[self.jieSuanDic[@"totalZkPrice"] floatValue]+[self.expressageDic[@"KdYfPrice"] floatValue])];
                        }
                        zhiFuVC.payType = [NSString stringWithFormat:@"%@",self.payDic[@"PaymentName"]];
                        [self.navigationController pushViewController:zhiFuVC animated:YES];
                    } else {
                        [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                    }
                }
                
            } failure:^(NSError *error) {
                NSLog(@"%@",error);
                [TFHUD addRemindHUD:self.view message:@"保存失败,请检查网络"];
            }];
        } else {
            [TFHUD addRemindHUD:self.view message:@"请添加收货地址"];
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        // 收货地址
        AddressViewController *addressVC = [[AddressViewController alloc] init];
        addressVC.delegate = self;
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        // 支付方式
        BuyTypeViewController *buyTypeVC = [[BuyTypeViewController alloc] init];
        buyTypeVC.delegate = self;
        buyTypeVC.payTypeArray = self.payTypeArray;
        [self.navigationController pushViewController:buyTypeVC animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 1) {
        // 送货方式
        ExpressViewController *expressVC = [[ExpressViewController alloc] init];
        expressVC.expressArray = self.expressageArray;
        expressVC.delegate = self;
        [self.navigationController pushViewController:expressVC animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 2) {
        // 发票信息
        BillInfoViewController *billInfoVC = [[BillInfoViewController alloc] init];
        billInfoVC.delegate = self;
        [self.navigationController pushViewController:billInfoVC animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 3) {
        // 选择优惠券
        CGFloat sumPrice = 0.0;
        NSArray *array = self.jieSuanDic[@"shopList"];
        if (array.count != 0) {
            for (NSDictionary *dic in array) {
                sumPrice = sumPrice + [dic[@"CommodityZPrice"] floatValue];
            }
        }
        SelectCouponsViewController *selectCouponVC = [[SelectCouponsViewController alloc] init];
        selectCouponVC.sumPrice = sumPrice;
        selectCouponVC.delegate = self;
        [self.navigationController pushViewController:selectCouponVC animated:YES];
    }
}
#pragma mark - 地址 delegate
- (void)sendAddressModel:(AddressModel *)model
{
    self.addressModel = model;
    [self.tableView reloadData];
}
#pragma mark - 支付方式 delegate
- (void)sendBuyTypeDic:(NSDictionary *)buyTypeDic
{
    self.payDic = buyTypeDic;
    [self.tableView reloadData];
}
#pragma mark - 送货方式 delegate
- (void)sendExpressDic:(NSDictionary *)expressDic
{
    self.expressageDic = expressDic;
    [self.tableView reloadData];
}
#pragma mark - 发票信息 delegate
- (void)sendBillDic:(NSDictionary *)billDic
{
    self.billDic = [NSDictionary dictionaryWithDictionary:billDic];
    [self.tableView reloadData];
}
#pragma mark - 优惠券 delegate
- (void)sendCouponsDic:(NSDictionary *)couponsDic
{
    self.couponsDic = [NSDictionary dictionaryWithDictionary:couponsDic];
    [self.tableView reloadData];
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
